﻿using System;
using System.Drawing;
using System.Diagnostics;

namespace iPhoneUI
{
    public static class ImageExtensions
    {
        /// <summary>
        /// Scales a rectangle (usually a clip rectangle) from a reference coordinate space
        /// into an image's coordinate space. Useful for getting the proper source rectangle 
        /// of an image that is stretched from its native size in one dimension
        /// </summary>
        /// <param name="image">The image</param>
        /// <param name="referenceBounds">The reference space</param>
        /// <param name="clipBounds">The target rectangle</param>
        /// <returns>the scaled rectangle</returns>
        public static Rectangle ScaleSourceRectangle(this Image image, Rectangle referenceBounds, Rectangle clipBounds)
        {
            Debug.Assert(image != null);

            // if the image is the same size and the reference there is no need to scale the clipbounds
            if (referenceBounds.Size == image.Size)
                return clipBounds;

            // translate the clipBounds into the coordinate system of the image
            // this is used to translate the image src rectangle when the image and reference are not the same sizes
            float dx = (float)image.Width / (float)referenceBounds.Width;
            float dy = (float)image.Height / (float)referenceBounds.Height;

            // calculate the scaled rectangle
            RectangleF rectF = new RectangleF((float)clipBounds.X * dx, (float)clipBounds.Y * dy, (float)clipBounds.Width * dx, (float)clipBounds.Height * dy);
            return Rectangle.Round(rectF);           
        }
    }
}
